package com.xm.email.core;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Properties;

@Data
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class MailInfo2 {
    //发送邮件的服务器的IP和端口
    private String mailServerHost;
    private String mailServerPort = "25";
    //邮件发送者的地址
    private String fromAddress;
    //邮件接收者的地址
    private String toAddress;
    //登陆邮件发送服务器的用户名和密码
    private String userName;
    private String password;
    //是否需要身份验证
    private boolean validate = false;
    //开启ssl
    private boolean ssl = false;
    //邮件主题
    private String subject;
    //邮件的文本内容
    private String content;
    //邮件附件上传路径
//    @JsonInclude(JsonInclude.Include.NON_NULL)
    private List<String> fileList;
    //邮件内容是否属于文本
    private boolean isHtml;
    private List<File> files;
    private Properties properties;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    public Properties getProperties() {
        Properties p = new Properties();
        p.put("mail.smtp.host", this.mailServerHost);
        p.put("mail.smtp.port", this.mailServerPort);
        p.put("mail.smtp.auth", validate ? "true" : "false");
        //-------当需使用SSL验证时添加，邮箱不需SSL验证时删除即可（测试SSL验证使用QQ企业邮箱）
        if(ssl) {
            String SSL_FACTORY="javax.net.ssl.SSLSocketFactory";
            p.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            p.put("mail.smtp.socketFactory.fallback", "false");
            p.put("mail.smtp.socketFactory.port", this.mailServerPort);

            //参考https://help.aliyun.com/document_detail/2679644.html
//			p.put("mail.smtp.ssl.enable", true);
//			p.put("mail.smtp.ssl.protocols", "TLSv1.2");

            //参考https://blog.csdn.net/wl1411956542/article/details/129196136
//			p.put("mail.mime.splitlongparameters", true);//据说高版本可能会出现因截断而引发的乱码问题

            MailSSLSocketFactory sf=null;
            try {
                sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
            } catch (GeneralSecurityException e) {
                log.error("创建邮件ssl socketFactory异常！", e);
            }
            p.put("mail.smtp.ssl.socketFactory", sf);
        }
        return p;
    }
}